let app = getApp();
let location = require("../../../mybehaviors/location/location");
Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    classifyShow:false,  //选择分类弹窗
    hoursShow:false, //选择时间弹窗
    addressShow: false, //选择地址弹窗
    applyShow: false,
    applyText: '',
    applyDescName:'', //消费券别名
    applyTextStatus:0,
    strShow:false,//选择街道
    classifyIndex:0, //一级分类索引
    secondIndex:null, //二级分类索引
    threeIndex:null, //三级分类索引
    uploadUrl:'upload.uploadPic', //上传图片
    anotherImgList:[],
    form:{
      store_name:'',
       //门店分类级ID
      first_category_id:0,
      second_category_id:0,
      third_category_id:0,
      //省市区街道的ID和地址和定位地址
      province_id:0,
      city_id:0,
      district_id:0,
      street_id:0,
      address:'',
      longitude:'',
      latitude:'',
      //营业日(星期),
      work_week:[],
      work_start_time:'',
      work_end_time:'',
      //店铺信息，企业执照
      store_mobile:'',
      staff_name:'',
      business_name:'',
      business_pics:'',
      another_pics:[],
      identity_front_image:'',
      identity_back_image:'',
      owner_name:'',
      owner_mobile:'',
      //商户简介
      store_desc:'',
      store_banner:'',
      store_logo:'',
    },
    //门店分类ID信息
    firstCategoryItem:{},
    secondCategoryItem:{},
    thirdCategoryItem:{},
    CategoryName:'',
    classifyList:[], //商户分类
    secondLevel:[],
    threeLevel:[],
    //地址信息
    addressName:'',
    streetName:'',//街道地址
    mapdataAddress:'', //定位地址信息
    //选择时间功能
    timeState:1, //判断是选择开始时间还是结束时间
    startTimeArr:[],
    endTimeArr:[],
    beginHour: "00",
    beginMinute: "00",
    endHour: "00",
    endMinute: "00",
    businessHours:'',
    timeArrValue:[0,0], //重置时间选择
    workWeek:[ //显示选中的日期数组
      {
        title: '周一',
        value: '1',
        checked:false
      },
      {
        title: '周二',
        value: '2',
        checked:false
      },
      {
        title: '周三',
        value: '3',
        checked:false
      },
      {
        title: '周四',
        value: '4',
        checked:false
      },
      {
        title: '周五',
        value: '5',
        checked:false
      },
      {
        title: '周六',
        value: '6',
        checked:false
      },
      {
        title: '周日',
        value: '7',
        checked:false
      }
    ],
    checkedAll:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.categoryList();
    try {
      wx.removeStorageSync('applyaddresspoint');
    } catch (e) {
      // Do something when catch error
    }
    this._getLocation((mapdata, e) => {
      this.setData({
        'form.longitude': e.lng,
        'form.latitude': e.lat,
        mapdataAddress: mapdata.address
      });
    });

    this.storeApply(); //商户申请协议
  },

  onShow() {
    try {
      let value = wx.getStorageSync('applyaddresspoint');
      if (value) {
        this.setData({
          'form.longitude': value.point.lng,
          'form.latitude': value.point.lat,
          mapdataAddress: value.address
        });
        // Do something with return value
      }
    } catch (e) {
      console.log(e);
    }
  },
  _initData() {
    let query  = {
      store_name:'',
       //门店分类级ID
      first_category_id:0,
      second_category_id:0,
      third_category_id:0,
      //省市区街道的ID和地址和定位地址
      province_id:0,
      city_id:0,
      district_id:0,
      street_id:0,
      address:'',
      longitude:'',
      latitude:'',
      //营业日(星期),
      work_week:[],
      work_start_time:'',
      work_end_time:'',
      //店铺信息，企业执照
      store_mobile:'',
      staff_name:'',
      business_name:'',
      business_pics:'',
      another_pics:[],
      identity_front_image:'',
      identity_back_image:'',
      owner_name:'',
      owner_mobile:'',
      //商户简介
      store_desc:'',
      store_banner:'',
      store_logo:'',
    };
    this.setData({
      form: query
    })
  },
  onStair(event) { //点击一级分类，获取下级分类
    const index = event.currentTarget.dataset.index,
          item =  event.currentTarget.dataset.item;
    let  secondLevelArr = [];
    if(item.has_many_child.length > 0) {
      secondLevelArr = item.has_many_child;
    }
    this.setData({
      classifyIndex: index,
      secondIndex: null,
      threeIndex: null,
      secondLevel:secondLevelArr,
      firstCategoryItem:item,
      secondCategoryItem:{}, //重置其他分类选择
      thirdCategoryItem: {},
      threeLevel:[]
    })
  },
  onSecond(event) { //查询二级分类下面的分类
    const index = event.currentTarget.dataset.index,
          item =  event.currentTarget.dataset.item;
    let  threeLevelArr = [];
    if(item.has_many_child.length > 0) {
      threeLevelArr = item.has_many_child;
    }
    this.setData({
      secondIndex: index,
      threeLevel:threeLevelArr,
      secondCategoryItem:item
    })
  },
  onThreeLevel(event) { //三级分类
    const index = event.currentTarget.dataset.index,
          item =  event.currentTarget.dataset.item;
    this.setData({
      threeIndex: index,
      thirdCategoryItem:item
    })
  },
  onClose(event) {
    let type = event.currentTarget.dataset.type;
    if(type === 'hours') {
      this.setData({
        hoursShow:false
      })
    } else {
      this.setData({
        classifyShow:false
      })
    }
  },
  onAddress() {
    this.setData({
      addressShow:true
    })
  },
  applyPopup() {
    if(this.data.applyTextStatus) {
      this.setData({
        applyShow:true
      })
    }
  },
  applyClose() {
    this.setData({
      applyShow:false
    })
  },
  getAddress(event) {
    let seleData = event.detail;
    let retCity = seleData[0].name + ' ' + seleData[1].name + ' ' + seleData[2].name;
    this.setData({
      addressName: retCity,
      'form.province_id':seleData[0].id,
      'form.city_id':seleData[1].id,
      'form.district_id':seleData[2].id,
      addressShow:false,
      strShow:true
    })
    this.getStreet(seleData[2].id);
  },
  streetShowbtn() {
    this.setData({
      streetShow: true
    });
  },
   //获取街道
  getStreet(param) {
    let that = this;
    let urlStr = "";
    urlStr += app.getNetAddresss("member.memberAddress.street");
    urlStr += '&district_id=' + param;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (!app._isTextEmpty(res.data) && res.data.length > 0) {
            that.setData({
              districtVal: res.data,
              strShow: true,
            });
          } else {
            that.setData({
              strShow: false
            });
          }
        } else {
          that.setData({
            strShow: false
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  streetConfirm(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      streetName: item.areaname,
      streetShow: false,
      'form.street_id': item.id,
    });
  },
  onclassifyAffirm() { //商户分类提交
    if (this.data.firstCategoryItem.id && this.data.secondCategoryItem.id && this.data.thirdCategoryItem.id) {
      let classifyNmae = `${this.data.firstCategoryItem.name}/${this.data.secondCategoryItem.name}/${this.data.thirdCategoryItem.name}`;
      this.setData({
        'form.first_category_id':this.data.firstCategoryItem.id,
        'form.second_category_id':this.data.secondCategoryItem.id,
        'form.third_category_id':this.data.thirdCategoryItem.id,
        CategoryName:classifyNmae,
        classifyShow:false
      })
      
    } else {
      wx.showToast({
        icon: 'none',
        title: '请选择分类',
        duration: 1500
      });
      return;
    }
    
  },
  onAffirm(event) {
     let  workWeek = this.data.workWeek,
        startTime = `${this.data.beginHour}:${this.data.beginMinute}`,
        endTime =  `${this.data.endHour}:${this.data.endMinute}`,
        startDate = '',
        endDate = '',
        workData = [],
        workIdData = [];
    workData = workWeek.filter(item => { //筛选所有选中的日期
      return  item.checked === true?item.value:false;
    });
    if(workData.length > 0) {
      if(Number(this.data.beginHour) < Number(this.data.endHour)) {  //记得加选择日期 
        workData.forEach((item) => {
          workIdData.push(item.value);
        });
        startDate = workData[0].title;
        endDate = workData[workData.length -1].title;
        this.setData({
          'form.work_week':workIdData,
          'form.work_start_time':startTime,
          'form.work_end_time':endTime,
          businessHours:`${startDate}至${endDate} ${startTime}-${endTime}`,
          hoursShow: false
        })
      } else {
        wx.showToast({
          icon: 'none',
          title: '结束时间不能大于开始时间',
          duration: 1500
        });
      }
    } else {
      wx.showToast({
        icon: 'none',
        title: '请选择店铺营业日期',
        duration: 1500
      });
    }
  },
  toGeolocation() {
    wx.navigateTo({
      url: '/packageC/o2o/o2oLocation_loc/o2oLocation_loc?tag=storeApply'
    });
  },
  checkChange(event) {
    this.setData({
      checkedAll: event.detail
    });
  },
  workWeekOn(event) {
    let index = event.currentTarget.dataset.index;
    let workWeekData = this.data.workWeek;
    workWeekData[index].checked = !workWeekData[index].checked;//修改选中的星期几
    this.setData({
      workWeek:workWeekData
    })
  },
  bindChangeTime(event) {
    const val = event.detail.value;
    let startTimeArr = this.data.startTimeArr; //开始时间
    let endTimeArr = this.data.endTimeArr; //结束时间
    if(this.data.timeState === 1) {
      this.setData({
        beginHour:startTimeArr[val[0]],
        beginMinute: endTimeArr[val[1]]
      })
    }
    if(this.data.timeState === 2) {
      this.setData({
        endHour:startTimeArr[val[0]],
        endMinute: endTimeArr[val[1]]
      })
    }
  },
  chooseTimeOn(event){ //切换开始和结束时间
    let state = event.currentTarget.dataset.state;
    this.setData({
      timeArrValue: [0,0]
    })
    this.setData({
      timeState:Number(state)
    })
  },
  onPupop(event) { //打开弹窗;
    let type = event.currentTarget.dataset.type;
    let startTimeArr = [];
    let endTimeArr = [];
    if(type === 'hours') {
      for(let i=0; i<24; i++) {
        i < 10 ? i = '0'+ i : i;
        startTimeArr.push(i)
      }
      for(let j=0; j<=59; j++) {
        j < 10 ? j = '0'+ j : j;
        endTimeArr.push(j)
      }
      this.setData({
        hoursShow:true,
        startTimeArr:startTimeArr,
        endTimeArr:endTimeArr
      })
    } else {
      this.setData({
        classifyShow:true
      })
    }
  },
  modelInput(event) {
    const item = event.currentTarget.dataset.item,
          itemValue = event.detail.value;
    this.setData({
      [item]:itemValue
    })
  },
  onRefund(){
    if (app._isTextEmpty(this.data.form.store_name)) {
      wx.showToast({
        icon: 'none',
        title: '请输入用户名',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.store_logo)) {
      wx.showToast({
        icon: 'none',
        title: '请上传商户logo',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.CategoryName)) {
      wx.showToast({
        icon: 'none',
        title: '请选择分类',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.addressName)) {
      wx.showToast({
        icon: 'none',
        title: '请选择地区',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.streetName)) {
      wx.showToast({
        icon: 'none',
        title: '请选择街道',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.address)) {
      wx.showToast({
        icon: 'none',
        title: '请输入详细地址',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.longitude) && app._isTextEmpty(this.data.form.latitude) ) {
      wx.showToast({
        icon: 'none',
        title: '请输入选择定位',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.businessHours)) {
      wx.showToast({
        icon: 'none',
        title: '请输入商户营业时间',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.store_mobile)) {
      wx.showToast({
        icon: 'none',
        title: '请输入店铺电话',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.staff_name)) {
      wx.showToast({
        icon: 'none',
        title: '请输入商户联系人',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.staff_mobile)) {
      wx.showToast({
        icon: 'none',
        title: '请输入联系电话',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.business_name)) {
      wx.showToast({
        icon: 'none',
        title: '请输入企业名称',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.business_pics)) {
      wx.showToast({
        icon: 'none',
        title: '请上传营业执照',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.another_pics)) {
      wx.showToast({
        icon: 'none',
        title: '请上传其他补充证件',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.owner_name)) {
      wx.showToast({
        icon: 'none',
        title: '请输入运营者姓名',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.owner_mobile)) {
      wx.showToast({
        icon: 'none',
        title: '请输入运营者手机号',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.identity_front_image)) {
      wx.showToast({
        icon: 'none',
        title: '请上传身份证正面照',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.identity_back_image)) {
      wx.showToast({
        icon: 'none',
        title: '请上传身份证背面照',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.checkedAll) && this.data.applyTextStatus) {
      wx.showToast({
        icon: 'none',
        title: '请同意入驻协议名称',
        duration: 1500
      });
      return;
    }
    let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.apply.storeApply");
    app._postNetWork({
      url: urlStr,
      data:this.data.form,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          this._initData();
          setTimeout(() => {
            wx.navigateBack({
              delta:1
            })
          },1000)
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
    
  },
  categoryList() {
    let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.category.categoryList");
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {

          this.setData({
            classifyList: res.data.list
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  storeApply() { //协议开关设置
    let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.apply.storeApplyPage");
    let json = {
      basic_info: 1
    };
    app._postNetWork({
      url: urlStr,
      data:json,
      success:  (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.setData({
            applyText: res.data.apply_text,
            applyTextStatus: res.data.apply_text_status,
            applyDescName: res.basic_info?.plugin_setting?.coupon_store.apply_desc_name
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  onRead(event) { //图片上传功能
    let itemName = event.currentTarget.dataset.itemname;
    console.log(event);
    let that = this;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths[0]);
        let photourl = tempFilePaths[0];
        wx.uploadFile({
          url: urlStr,
          filePath: photourl,
          name: 'file',
          success(resdata) {
            let res = JSON.parse(resdata.data);
            if (res.result == 1) {
              that.setData({
                [itemName]: res.data.img_url
              });
            } else {
              wx.showToast({
                icon: 'none',
                title: res.msg,
                duration: 1500
              });
            }
          }
        });
      }
    });
  },
  onanotherPics(){
    let that = this;
    let ig = '2';
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // var tempFilePaths = res.tempFilePaths
        that.unload({
          tempFilePaths: res.tempFilePaths
        }, ig);
      }
    });
  },
  delIntu_2(event) {
    let index = event.currentTarget.dataset.id;
    let imgList = this.data.anotherImgList;
    imgList.splice(index,1); //删除选择的图片
    this.setData({
      'form.another_pics': this.data.anotherImgList
    })
  },
  //多张上传方法
  unload(data, ig) {
    console.log(ig);
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    let that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: urlStr,
      filePath: data.tempFilePaths[i],
      name: 'file',
      formData: null,
      success(resdata) {
        var res = JSON.parse(resdata.data);
        console.log(res.data.img_url);
        if (ig == '1') {
          that.data.anotherImgList.push(res.data.img_url);
          that.setData({
            'form.another_pics': that.data.anotherImgList
          });
        } else if (ig == 2) {
          that.data.anotherImgList.push(res.data.img_url);
          that.setData({
            'form.another_pics': that.data.anotherImgList
          });
        }
        console.log(that.data.anotherImgList);
      },
      fail(e) {
        fail++;
      },
      complete(e) {
        i++;
        if (i == data.tempFilePaths.length) { //当图片传完时，停止调用
          console.log('执行完毕');
          console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.unload(data, ig); //递归，回调自己
        }
      }
    });

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})